package role

import (
	"ZHONGYIHANGYAN/bean/dbModel"
	"ZHONGYIHANGYAN/bean/request"
	"ZHONGYIHANGYAN/bean/response"
	commUtils "ZHONGYIHANGYAN/commUtils"
	"fmt"
)

// 获取角色列表
func (manage *RoleManage) GetRoleList(query *request.GetRoleListQuery) ([]response.GetRoleListResponseInfo, error) {
	db := manage.DataBase.DB()
	tx := db.Model(&dbModel.Role{})
	
	// 按名称过滤
	if query.Name != "" {
		tx = tx.Where("name LIKE ?", "%"+query.Name+"%")
	}

	// 按名称排序查询所有角色
	var roleList []response.GetRoleListResponseInfo
	if err := tx.Order("name ASC").Find(&roleList).Error; err != nil {
		return nil, err
	}

	return roleList, nil
}


// 添加或修改角色信息
func (manage *RoleManage) AddOrUpdateRole(role *request.AddOrUpdateRoleQuery) error {
	db := manage.DataBase.DB()

	isUpdate := role.Id != ""


	if !isUpdate {
		roleToCreate := dbModel.Role{
			Id:       commUtils.GenUUID(),
			Name: role.Name,
			Desc: role.Desc,
			DefaultRole: role.DefaultRole,
		}
		if err := db.Create(&roleToCreate).Error; err != nil {
			return err
		}
	} else {
		idToUpdate := role.Id
		updateData := map[string]interface{}{
			"name": role.Name,
			"desc": role.Desc,
			"default_role": role.DefaultRole,
		}

		result := db.Model(&dbModel.Role{}).Where("id = ?", idToUpdate).Updates(updateData)
		if result.Error != nil {
			return result.Error
		}
		// 检查是否有记录被更新
		if result.RowsAffected == 0 {
			return fmt.Errorf("更新角色失败：ID 为 %d 的记录未找到", idToUpdate)
		}
	}
	return nil
}

// 删除角色
func (manage *RoleManage) DeleteRole(roleIds []string) error {
	if len(roleIds) == 0 {
		return nil
	}

	db := manage.DataBase.DB()
	result := db.Where("id IN ?", roleIds).Delete(&dbModel.Role{})
	if result.Error != nil {
		return result.Error
	}
	if result.RowsAffected == 0 {
		return fmt.Errorf("没有找到要删除的记录，ID列表可能无效或记录已被删除")
	}
	return nil
}